<template>
	<view class="pupop">
		<view class="popup-box" :animation="animationData">
			<view class="pupop-btn">
				<view @tap="cancel">取消</view>
				<view @tap="confirm" :style="`color: ${confirmBtnColor}`">确定</view>
			</view>
			<picker-view
				:value="selectdRegionValue"
				:indicator-style="indicatorStyle"
				@change="bindChange"
				class="picker-view"
				v-if="provinceList.length > 0"
			>
				<!-- 省区域开始 -->
				<picker-view-column>
					<view 
						class="item"
						v-for="(item,index) in provinceList" :key="index"
						:style="index == provinceIndex ? `color: ${selectedColor}` : ``"
					>
						{{item.name}}
					</view>
				</picker-view-column>
				<!-- 省区域结束 -->

				<!-- 市区域开始 -->
				<picker-view-column>
					<view
						class="item"
						v-for="(item,index) in cityList" :key="index"
						:style="index == cityIndex ? `color: ${selectedColor}` : ``"
					>
						{{item.name}}
					</view>
				</picker-view-column>
				<!-- 市区域结束 -->

				<!-- 区县区域开始 -->
				<picker-view-column v-if="column == 3">
					<view
						class="item"
						v-for="(item,index) in areaList" :key="index"
						:style="index == areaIndex ? `color: ${selectedColor}` : ``"
					>
						{{item.name}}
					</view>
				</picker-view-column>
				<!-- 区县区域结束 -->
			</picker-view>
		</view>
		<view @tap="close" @touchmove.stop.prevent :class="visible ? 'pupop-model' : 'pupop-models'"></view>
	</view>
</template>

<script setup lang="ts">
import type { RegionTree } from '@/types/common'
import { nextTick, ref, watch } from 'vue'

// --------------- 定义全局变量开始 ---------------
// 已选中地区
const selectdRegionValue = ref<number[]>([])

// 省列表
const provinceList = ref<RegionTree[]>([])

// 市列表
const cityList = ref<RegionTree[]>([])

// 区域列表
const areaList = ref<RegionTree[]>([])

// 指示器样式
const indicatorStyle = ref(`height: 50px;`)

// 省索引
const provinceIndex = ref<number>(0)

// 省索引
const cityIndex = ref<number>(0)

// 区域索引
const areaIndex = ref<number>(0)

// 动画数据
const animationData = ref({})

// 接收父组件参数
const props = withDefaults(defineProps<{
	// 地区数据
	regionList: RegionTree[]

	// 列数默认3【2=省市、3=省市区】
    column?: number

	// 默认选中
    defaultValue?: []

    visible?: boolean

    maskCloseAble?: boolean

	// 选中颜色
	selectedColor?: string

	// 确认按钮颜色
	confirmBtnColor?: string
}>(), {
	column: 3,
    defaultValue: [] as never,
    visible: false,
    maskCloseAble: true,
	selectedColor: '#27BA9B;',
	confirmBtnColor: '#27BA9B;'
})

const emit = defineEmits(['cancel', 'confirm'])
// --------------- 定义全局变量结束 ---------------



// ---------------- 初始化地区开始 ----------------
const init = () => {
	// 组装省数据
	let tempProvinceList: any = []
	props.regionList.filter((item: any) => {
		tempProvinceList.push({
			id: item.id,
			name: item.name
		})
	})
	provinceList.value = [...tempProvinceList]

	// 处理默认选中
	if (props.defaultValue.length == 0) {
		cityList.value = props.regionList[0]?.children
		areaList.value = props.regionList[0]?.children[0].children
	} else {
		if (Array.isArray(props.defaultValue) && props.defaultValue.length >= 2) {
			console.log(props.defaultValue)
			let province = props.defaultValue[0]
			let city = props.defaultValue[1]

			provinceIndex.value = 0
			cityIndex.value = 0
			areaIndex.value = 0

			// 获取省索引
			provinceIndex.value = props.regionList.findIndex((obj: any) => {
				return obj.id == province
			})
			provinceIndex.value = provinceIndex.value >= 0 ? provinceIndex.value : 0

			// 获取市索引
			cityList.value = props.regionList[provinceIndex.value]?.children || []
			cityIndex.value = cityList.value.findIndex((obj: any) => {
				return obj.id == city
			})
			cityIndex.value = cityIndex.value >= 0 ? cityIndex.value : 0

			// 获取区域索引
			areaList.value = cityList.value[cityIndex.value]?.children || []
			if (props.defaultValue.length > 2) {
				areaIndex.value = areaList.value.findIndex((obj: any) => {
					return obj.id == props.defaultValue[2]
				})
			}
			areaIndex.value = areaIndex.value >= 0 ? areaIndex.value : 0

			// 组装选中的地区索引
			nextTick(() => {
				if (props.column == 3) {
					selectdRegionValue.value = [provinceIndex.value, cityIndex.value, areaIndex.value]
				} else if (props.column == 2) {
					selectdRegionValue.value = [provinceIndex.value, cityIndex.value]
				}
			})
		} else {
			uni.showToast({
				title: '地区编码格式不正确',
				icon: 'none'
			})
			console.log('地区编码格式不正确')
		}
	}
	
	changeActive()
}
// ---------------- 初始化地区结束 ----------------



// --------------- 处理确认功能开始 ---------------
const confirm = () => {
	if (props.column == 3) { // 省市区
		emit('confirm', {
			// 省Id
			provinceId: props.regionList[provinceIndex.value].id,

			// 市Id
			cityId: props.regionList[provinceIndex.value].children[cityIndex.value].id,

			// 区域Id
			districtId: props.regionList[provinceIndex.value].children[cityIndex.value].children[areaIndex.value].id,

			// 地区名称
			regionName: props.regionList[provinceIndex.value].name + '-' + props.regionList[provinceIndex.value].children[cityIndex.value].name + '-' + props.regionList[provinceIndex.value].children[cityIndex.value].children[areaIndex.value].name,

			// 省名称
			provinceName: props.regionList[provinceIndex.value].name,

			// 市名称
			cityName: props.regionList[provinceIndex.value].children[cityIndex.value].name,

			// 区域名称
			districtName: props.regionList[provinceIndex.value].children[cityIndex.value].children[areaIndex.value].name
		})
	} else if (props.column == 2) { // 省市
		emit('confirm', {
			// 省Id
			provinceId: props.regionList[provinceIndex.value].id,

			// 市Id
			cityId: props.regionList[provinceIndex.value].children[cityIndex.value].id,

			// 地区名称
			regionName: props.regionList[provinceIndex.value].name + '-' + props.regionList[provinceIndex.value].children[cityIndex.value].name,

			// 省名称
			provinceName: props.regionList[provinceIndex.value].name,

			// 市名称
			cityName: props.regionList[provinceIndex.value].children[cityIndex.value].name
		})
	} else {
		uni.showToast({
			title: '目前column只能传2和3',
			icon: 'none'
		})
	}
}
// --------------- 处理确认功能结束 ---------------



// --------------- 处理动画功能开始 ---------------
const changeActive = () => {
	let active: any = '-415px'
	if (props.visible) {
		active = 0
	}
	let animation = uni.createAnimation({
		duration: 400,
		timingFunction: 'linear'
	})
	animation.bottom(active).step()
	animationData.value = animation.export()
}
// --------------- 处理动画功能结束 ---------------



// --------------- 绑定改变功能开始 ---------------
const bindChange = (e: any) => {
	e.detail.value[0] = e.detail.value[0] || 0
	e.detail.value[1] = e.detail.value[1] || 0
	e.detail.value[2] = e.detail.value[2] || 0
	
	if (e.detail.value[0] != provinceIndex.value) {
		// console.log('监听省')
		provinceChange(e.detail.value[0])
	} else if (e.detail.value[1] != cityIndex.value) {
		// console.log('监听市')
		cityChange(e.detail.value[1])
	} else if (e.detail.value[2] != areaIndex.value) {
		// console.log('监听区域')
		areaChange(e.detail.value[2])
	}
}
// --------------- 绑定改变功能结束 ---------------



// ---------------- 监听省变化开始 ----------------
const provinceChange = (e: any) => {
	provinceIndex.value = e
	cityIndex.value = 0
	areaIndex.value = 0
	selectdRegionValue.value = [...[e, 0, 0]]
	cityList.value = props.regionList[e]?.children
	areaList.value = props.regionList[e]?.children[0].children
}
// ---------------- 监听省变化结束 ----------------



// ---------------- 监听市变化结束 ----------------
const cityChange = (e: any) => {
	cityIndex.value = e
	areaIndex.value = 0
	selectdRegionValue.value = [...[provinceIndex.value, e, 0]] as never
	cityList.value = props.regionList[provinceIndex.value]?.children
	areaList.value = props.regionList[provinceIndex.value]?.children[e].children
}
// ---------------- 监听市变化结束 ----------------



// --------------- 监听地区变化开始 ---------------
const areaChange = (e: any) => {
	areaIndex.value = e
}
// --------------- 监听地区变化结束 ---------------



// --------------- 点击蒙层功能开始 ---------------
const close = () => {
	if (props.maskCloseAble) {
		cancel()
	}
}
// --------------- 点击蒙层功能结束 ---------------



// --------------- 处理取消功能开始 ---------------
const cancel = () => {
	emit('cancel')
}
// --------------- 处理取消功能结束 ---------------



// --------------- 处理监控功能开始 ---------------
watch(() => props.visible, () => {
	changeActive()
})

watch(() => props.defaultValue, () => {
	init()
})
// --------------- 处理监控功能结束 ---------------


// 导出
defineExpose({
    init
})
</script>

<style scoped lang="scss">
	.pupop {
		.popup-box {
			position: fixed;
			left: 0;
			bottom: -315px;
			z-index: 99999;
			background: #fff;
			padding-bottom: 50px;
			.pupop-btn{
				height: 40px;
				display: flex;
				align-items: center;
				padding: 0 30upx;
				justify-content: space-between;
			}
		}
		.pupop-model {
			position: fixed;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 9999;
			background: rgba(0, 0, 0, .5);
		}
		.pupop-models{
			display: none;
		}
		.picker-view {
			width: 750rpx;
			height: 225px;
			margin-top: 20rpx;
		}
		.item {
			height: 50px;
			align-items: center;
			justify-content: center;
			text-align: center;
			line-height: 50px;
		}
	}
</style>
